//
//  UIView+HJTapBlock.m
//  TestGroup
//
//  Created by HeJia on 16/7/29.
//  Copyright © 2016年 HeJia. All rights reserved.
//

#import "UIView+HJTapBlock.h"
#import <objc/runtime.h>

#define VIEW_TAPFUNC "_viewTapFunc"
#define VIEW_GESTURE "_viewGesture"
#define view_LongTapFunc "view_LongTapFunc"
#define view_LongTap_GESTURE "view_LongTap_GESTURE"
@implementation UIView (HJTapBlock)
@dynamic tapFunc;

-(void) setTapFunc:(TapFunc)tapFunc
{
    if(!self.userInteractionEnabled) self.userInteractionEnabled = YES;
    
    UITapGestureRecognizer *rec = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    [self addGestureRecognizer:rec];
    rec.delegate = self;
    objc_setAssociatedObject(self, VIEW_TAPFUNC, tapFunc, OBJC_ASSOCIATION_COPY);
    objc_setAssociatedObject(self, VIEW_GESTURE, rec, OBJC_ASSOCIATION_RETAIN);
    
}

-(TapFunc) tapFunc{
    return objc_getAssociatedObject(self, VIEW_TAPFUNC);
}

-(void) tap:(UITapGestureRecognizer *)tap{
    if(self.tapFunc)
        self.tapFunc();
}

- (void)setLongTapFunc:(LongTapFunc)longTapFunc{
    if(!self.userInteractionEnabled) self.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *gesture=[[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longClick:)];
    gesture.minimumPressDuration=0.5;
    [self addGestureRecognizer:gesture];
    gesture.delegate = self;
    objc_setAssociatedObject(self, view_LongTapFunc, longTapFunc, OBJC_ASSOCIATION_COPY);
    objc_setAssociatedObject(self, view_LongTap_GESTURE, gesture, OBJC_ASSOCIATION_RETAIN);
}

-(void)longClick:(UILongPressGestureRecognizer *)longTap{
    if (longTap.state == UIGestureRecognizerStateBegan) {
        if(self.longTapFunc)
             self.longTapFunc();
    }
}

- (LongTapFunc)longTapFunc{
   return  objc_getAssociatedObject(self, view_LongTapFunc);
}

-(bool)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{
//    UITapGestureRecognizer *rec = objc_getAssociatedObject(self, VIEW_GESTURE);
//    if(gestureRecognizer == rec){
//        CGPoint pt = [touch locationInView:self];
//        UIView *v = [self hitTest:pt withEvent:nil];
//        if(v == self){
//            return YES;
//        }else{
//            return NO;
//        }
//    }else{
//        return YES;
//    }
      return YES;
}

@end
